from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import UserForm, ResetForm


@login_required  # 登录才能打开页面
def index(request):
    return render(request, 'index.html')


# 登录
def my_login(request):
    if request.method == 'GET':
        # 1, 首先检查session，判断用户是否第一次登录，如果不是，则直接重定向到首页
        if 'username' in request.session:  # request.session 类字典对象
            return redirect("/login/index/?username=%s" % request.session['username'])
        # 2, 然后检查cookie，是否保存了用户登录信息
        if 'username' in request.COOKIES:
            # 若存在则赋值回session，并重定向到首页
            request.session['username'] = request.COOKIES['username']
            return redirect("/login/index/?username=%s" % request.session['username'])
        # 不存在则重定向登录页，让用户登录
        return render(request, 'login.html')
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        # 判断表单是否有效
        if user_form.is_valid():
            name = request.POST['username']
            pwd = request.POST['password']
            # 验证账号密码
            user = authenticate(username=name, password=pwd)
            if user is not None:
                # 将用户数据保存在 session 中，即实现了登录动作
                login(request, user)
                # 跳转到index界面，同时传递用户名到url路径中
                return redirect("/login/index/?username=%s" % name)
            else:
                error_msg = '用户名或密码错误'
                return render(request, 'login.html', {'error_msg': error_msg})
    return render(request, 'login.html')


# 重置密码
def reset(request):
    if request.method == 'POST':
        reset_form = ResetForm(request.POST)
        if reset_form.is_valid():
            name = request.POST['username']
            old_pwd = request.POST['old_password']
            new_pwd = request.POST['new_password1']
            auth = authenticate(username=name, password=old_pwd)
            if auth is not None:
                user = User.objects.get(username=name)
                user.set_password(new_pwd)
                user.save()
                return redirect("/login/")
            else:
                error_msg = '用户名或密码错误'
                return render(request, 'reset.html', {'error_msg': error_msg})
    return render(request, 'reset.html')


# 登出
def my_logout(request):
    # 删除session
    logout(request)
    # 跳转回login界面
    response = redirect("/login/")
    # 删除cookie
    response.delete_cookie('username')
    return response
